<template>
	<view class="container">
		<form @submit.prevent="handleSubmit" class="form-container">
			<view class="form-section" style="margin-top: -10rpx;">
				<text class="section-title">软件图标</text>
				<view class="icon-upload-group">
					<view class="icon-box" @click="chooseIcon">
						<image v-if="form.images[0]" :src="form.images[0]" class="icon-preview" mode="aspectFill" />
						<view v-else class="icon-placeholder">
							<text class="fa-regular fa-image icon-placeholder-icon"></text>
							<text class="icon-placeholder-text">点击上传</text>
						</view>
					</view>
					<view class="icon-upload-tip">
						<text class="tip-paragraph">建议正方形图片（PNG/JPG/SVG），将实时预览。</text>
						<text class="tip-paragraph mt-1">点击方框选择图片。</text>
					</view>
				</view>
			</view>
			<view class="form-section">
				<text class="section-title">软件截图</text>
				<view style="display: grid;grid-template-columns: repeat(3,1fr);gap: 24rpx;">
					<view style="position: relative;" class="image-placeholder" v-for="(image, index) in form.images"
						:key="index" @click="previewImage(index)">
						<image :src="image" mode="aspectFill" style="width: 100%;height: 100%;border-radius: 10rpx;" />
						<view class="image-delete" @click.stop="deleteImage(index)">
							<text class="iconfont icon-delete"></text>
						</view>
					</view>
					<view v-if="form.images.length==0" style="border: 2px dashed #d1d5db;" class="image-placeholder"
						@click="uploadImage">
						<view style="display: flex;flex-direction: column;color: #9ca3af;align-items: center;">
							<text class="iconfont icon-xiangji" style="font-size: 32px;"></text>
							<text style="font-size: 12px;color: #6b7280;">添加图片</text>
						</view>
					</view>
					<view v-else style="border: 2px dashed #d1d5db;" class="image-placeholder" @click="uploadImage">
						<text class="iconfont icon-plus" style="font-size: 32px;color: #9ca3af;"></text>
					</view>
				</view>
			</view>
			<view class="form-section">
				<text class="section-title">基本信息</text>
				<view class="grid-form">
					<view class="form-item col-span-2">
						<text class="input-label">是否官方正版</text>
						<view class="radio-group">
							<label class="radio-item" @click="form.isOfficial = true">
								<view class="radio-dot" :class="{ 'radio-dot-checked': form.isOfficial }"></view>
								<text>是</text>
							</label>
							<label class="radio-item" @click="form.isOfficial = false">
								<view class="radio-dot" :class="{ 'radio-dot-checked': !form.isOfficial }"></view>
								<text>否 / 非官方</text>
							</label>
						</view>
					</view>
					<view class="form-item col-span-1">
						<text class="input-label required">软件名称</text>
						<input v-model="form.title" type="text" placeholder="例如：Microsoft Office 2021"
							class="text-input" required />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label required">软件描述</text>
						<input v-model="form.description" type="text" placeholder="例如：办公用品" class="text-input"
							required />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label required">厂商</text>
						<input v-model="form.vendor" type="text" placeholder="例如：Microsoft Corporation"
							class="text-input" required />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label required">版本</text>
						<input v-model="form.version" type="text" placeholder="例如：2021" class="text-input" required />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label">大小</text>
						<input v-model="form.pkgSize" type="text" placeholder="例如：3.2GB" class="text-input" />
					</view>

					<view class="form-item col-span-1">
						<text class="input-label">分类</text>
						<picker @change="form.category = categories[$event.detail.value]"
							:value="categories.findIndex(c => c === form.category)" :range="categories"
							class="picker-input">
							<view class="picker-text">{{ form.category || '请选择分类' }}</view>
						</picker>
					</view>
					<view class="form-item col-span-2">
						<text class="input-label">标签（逗号分隔）</text>
						<input v-model="form.tagsInput" type="text" placeholder="例如：办公, 协作, 演示" class="text-input" />
						<text class="input-tip">可输入多个标签，使用中文或英文逗号分隔。</text>
					</view>
					<view style="display: flex;gap: 20rpx;">
						<view class="form-item col-span-1">
							<text class="input-label">评分</text>
							<input v-model="form.rating" type="digit" placeholder="例如：4.5" class="text-input"
								@blur="onRatingInput" />
						</view>
						<view class="form-item col-span-1">
							<text class="input-label">下载量</text>
							<input v-model="form.dCount" type="number" placeholder="例如：78" class="text-input" />
						</view>
					</view>
				</view>
			</view>
			<view class="form-section">
				<text class="section-title">支持操作系统</text>
				<view class="platform-checkbox-group">
					<label v-for="(item, index) in platformList" :key="index" class="platform-checkbox"
						:class="{ 'platform-checked': form.platforms.includes(item.value) }"
						@click="togglePlatform(index)">
						<image :src="item.icon" mode="aspectFit" style="width: 50rpx;height: 50rpx;" />
						<text>{{ item.label }}</text>
					</label>
				</view>
			</view>

			<view class="form-section">
				<text class="section-title">网盘下载</text>
				<view class="grid-form">
					<view class="form-item col-span-1">
						<text class="input-label">蓝奏云盘</text>
						<input v-model="form.links.lanzou" type="url" placeholder="https://pan.lanzou.com/..."
							class="text-input" />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label">百度网盘</text>
						<input v-model="form.links.baidu" type="url" placeholder="https://pan.baidu.com/..."
							class="text-input" />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label">阿里云盘</text>
						<input v-model="form.links.aliyun" type="url" placeholder="https://www.alipan.com/s/..."
							class="text-input" />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label">迅雷云盘</text>
						<input v-model="form.links.xunlei" type="text" placeholder="thunder:// 或 magnet:?xt=..."
							class="text-input" />
					</view>
					<view class="form-item col-span-1">
						<text class="input-label">夸克云盘</text>
						<input v-model="form.links.quark" type="url" placeholder="https://pan.quark.cn/s/..."
							class="text-input" />
					</view>
				</view>
				<text class="input-tip mt-1">至少填写一个下载方式。</text>
			</view>

			<view class="form-section">
				<text class="section-title">软件介绍 (富文本内容)</text>
				<view class="editor-wrapper">
					<editor id="editor" class="ql-container" placeholder="开始输入..." show-img-size show-img-toolbar
						show-img-resize  @input="contentChange" >
					</editor>
				</view>
			</view>
		</form>
	</view>
	<view class="fixed-bottom-bar">
		<button form-type="submit" @click="handleSubmit" class="submit-btn-fixed">
			上架
		</button>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue';
	import {
		onShareAppMessage
	} from '@dcloudio/uni-app'
	import api from '@/utils/api.js'
	const categories = ['请选择分类', '办公软件', '编程工具', '系统软件', '脚本代码', '图像处理'];

	const platformList = [{
			label: 'MacOS',
			value: 'macos',
			icon: '/static/ios.png'
		},
		{
			label: 'Windows',
			value: 'windows',
			icon: '/static/windows.png'
		},
		{
			label: 'Android',
			value: 'android',
			icon: '/static/android.png'
		},
		{
			label: 'Linux',
			value: 'linux',
			icon: '/static/linux.png'
		}
	]

	const contentChange = (res) => {
		form.content=res.target.text
		
		console.log(form.content);
		// // #ifdef APP-PLUS || MP-WEIXIN || H5
		// uni.createSelectorQuery().select('#editor').context((res) => {
		// 	console.log(res);
		// }).exec()
		// // #endif
		
	}

	const onRatingInput = (e) => {
		let val = parseFloat(e.detail.value);
		if (isNaN(val)) { // 清空或输入非法字符
			form.rating = '';
			return;
		}
		if (val > 5) {
			uni.showToast({
				title: '评分最高为 5',
				icon: 'none'
			});
			val = 5;
		} else if (val < 0) {
			uni.showToast({
				title: '评分最低为 0',
				icon: 'none'
			});
			val = 0;
		}
		form.rating = val.toFixed(1);
	};

	const form = reactive({
		title: '',
		description: '',
		vendor: '',
		version: '',
		rating: null,
		dCount: '',
		pkgSize: '',
		category: categories[0],
		tagsInput: '', // 原始输入的标签字符串
		platforms: [],
		images: [], // 本地临时路径（只做预览）
		imageUrls: [], // 上传完成后的云端 url
		isOfficial: true, // true: 是官方正版, false: 否/非官方
		links: {
			lanzou: '',
			baidu: '',
			aliyun: '',
			xunlei: '',
			quark: '',
		},
		content: '', // 替代富文本编辑器
	});


	const togglePlatform = (index) => {
		// 1. 根据传入的索引获取平台的实际值，例如 'ios' 或 'windows'
		const platformValue = platformList[index].value;
		// 2. 查找该值在 form.platforms 数组中的位置
		const currentPlatformIndexInForm = form.platforms.indexOf(platformValue);
		if (currentPlatformIndexInForm === -1) {
			// 未选中，则添加
			form.platforms.push(platformValue);
		} else {
			// 已选中，则移除
			form.platforms.splice(currentPlatformIndexInForm, 1);
		}
	};


	const uploadImage = () => {
		// #ifdef MP-WEIXIN
		uni.chooseMedia({
			count: 5 - form.images.length,
			mediaType: ['image'],
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const paths = res.tempFiles.map(file => file.tempFilePath);
				form.images.push(...paths);
			}
		})
		// #endif
		// #ifdef H5
		uni.chooseImage({
			count: 5 - form.images.length,
			mediaType: ['image'],
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				console.log(res);
				form.images.push(...res.tempFilePaths)
			}
		})
		// #endif
	}

	// 删除照片
	const deleteImage = (index) => {
		form.images.splice(index, 1)
	}

	const chooseIcon = () => {
		// #ifdef MP-WEIXIN
		uni.chooseMedia({
			count: 1 - form.images.length,
			mediaType: ['image'],
			sizeType: ['compressed'],
			sourceType: ['album'],
			success: (res) => {
				const paths = res.tempFiles.map(file => file.tempFilePath);
				form.images.push(...paths);
			}
		})
		// #endif
		// #ifdef H5
		uni.chooseImage({
			count: 1 - form.images.length,
			mediaType: ['image'],
			sizeType: ['compressed'],
			sourceType: ['album'],
			success: (res) => {
				console.log(res);
				form.images.push(...res.tempFilePaths)
			}
		})
		// #endif
	};

	/**
	 * 批量上传图片
	 * @param {Array<string>} filePaths - 图片文件路径的数组
	 * @returns {Promise<Array<any>>} - 包含所有图片上传结果的 Promise 数组
	 */
	const uploadMultipleImages = async (filePaths) => {
		if (!Array.isArray(filePaths) || filePaths.length === 0) {
			console.warn('没有提供文件路径进行上传。');
			return [];
		}
		const uploadPromises = filePaths.map(filePath => {
			return api.common.uploadImage(filePath)
				.then(result => {
					return result;
				})
				.catch(error => {
					console.error(`图片上传失败: ${filePath}`, error);
					return null;
				});
		});
		try {
			const results = await Promise.all(uploadPromises);
			return results.filter(result => result !== null); // 过滤掉失败的上传结果
		} catch (error) {
			console.error('批量图片上传过程中发生错误:', error);
			throw error;
		}
	};


	const formToData = () => {
		const data = {
			title: form.title.trim(),
			description: form.description.trim(),
			vendor: form.vendor.trim(),
			version: form.version.trim(),
			pkgSize: form.pkgSize.trim(),
			rating: form.rating,
			dCount: form.dCount === '' ? 0 : parseInt(form.dCount, 10) || 0,
			category: form.category === categories[0] ? '' : form.category,
			supportSys: form.platforms.join(','), // 复制数组
			imageUrls: [...form.imageUrls],
			isOfficial: form.isOfficial === true ? 1 : 0,
			// tags: form.tagsInput.toString().split(/[,，]/).map(s => s.trim()).filter(Boolean),
			tags: form.tagsInput.trim(),
			links: {
				lanzou: form.links.lanzou.trim(),
				baidu: form.links.baidu.trim(),
				aliyun: form.links.aliyun.trim(),
				xunlei: form.links.xunlei.trim(),
				quark: form.links.quark.trim(),
			},
			// introduction: `<p>${form.content.replace(/\n/g, '<br>')}</p>`, // 简单的文本转HTML
			introduction: form.content
		};
		return data;
	};

	const validateData = (data) => {
		const errors = [];
		if (!data.title) errors.push("软件名称为必填项");
		if (!data.vendor) errors.push("厂商为必填项");
		if (!data.version) errors.push("版本为必填项");
		const hasAnyLink = Object.values(data.links || {}).some(v => !!v);
		if (!hasAnyLink) errors.push("至少提供一个下载方式（百度/阿里/迅雷/夸克）");
		return errors;
	};

	// 上传
	const handleSubmit = async () => {
		if (form.images.length > 0) {
			const uploadedImageResults = await uploadMultipleImages(form.images);
			const imageUrls = uploadedImageResults.map(item => item.url);
			form.imageUrls = imageUrls;
		} else {
			uni.showModal({
				title: '图片上传',
				content: '至少上传一张图片',
			});
			return;
		}
		const data = formToData();
		const errors = validateData(data);

		if (errors.length) {
			uni.showModal({
				title: '验证失败',
				content: `请修正以下问题：\n${errors.join('\n')}`,
				showCancel: false
			});
			return;
		}
		// 模拟数据提交逻辑
		try {
			const result = await api.app.publish(data)
			if (result.code == 200) {
				uni.showToast({
					title: '上架成功！',
					icon: 'success'
				});
			}
			// 重置表单
			Object.assign(form, {
				title: '',
				description: '',
				vendor: '',
				version: '',
				rating: null,
				dCount: '',
				pkgSize: '',
				category: categories[0],
				tagsInput: '',
				platforms: [],
				images: [],
				imageUrls: [],
				isOfficial: true, // 重置为默认值
				links: {
					lanzou: '',
					baidu: '',
					aliyun: '',
					xunlei: '',
					quark: ''
				},
				content: '',
			});
		} catch (err) {
			console.error('上架失败', err);
			uni.showToast({
				title: '上架失败，请重试',
				icon: 'error'
			});
		}
	};

	// --- 新增：图片预览功能 ---
	const previewImage = (currentImageIndex) => {
		// 1. 获取所有图片的路径列表 (URLs)
		const urls = form.images;
		// 2. 确定当前点击的图片是列表中的哪一个
		const currentUrl = urls[currentImageIndex];
		// 3. 调用 uni.previewImage API
		uni.previewImage({
			// 当前显示图片的链接/路径
			current: currentUrl,
			// 需要预览的图片链接/路径列表
			urls: urls,
			// 确保动画效果和用户体验
			indicator: 'default', // 或 'none'
			loop: true // 允许循环预览
		});
	};

	// 分享朋友
	onShareAppMessage(() => {
		return {
			title: '发布软件',
			path: '/pages/publish/publish'
		};
	})
</script>

<style scoped>
	.container {
		background-color: #f9fafb;
	}

	.form-container {
		background-color: #ffffff;
		padding: 32rpx;
		display: flex;
	}

	.form-section {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
		margin-top: 10rpx;
	}

	.section-title {
		font-size: 18px;
		font-weight: bold;
		color: #1f2937;
		margin-top: 10rpx;
		display: block;
	}

	.input-label {
		font-size: 28rpx;
		color: #4b5563;
		margin-bottom: 8rpx;
		display: block;
	}

	.required::after {
		content: " *";
		color: #ef4444;
	}

	.input-tip {
		font-size: 24rpx;
		color: #6b7280;
		margin-top: 8rpx;
		display: block;
	}

	.text-input,
	.picker-input {
		border: 2rpx solid #d1d5db;
		border-radius: 16rpx;
		padding: 16rpx 24rpx;
		font-size: 30rpx;
	}

	.picker-input {
		display: flex;
		align-items: center;
	}

	.picker-text {
		color: #1f2937;
	}

	.image-placeholder {
		aspect-ratio: 1 / 1;
		background-color: #f3f4f6;
		border-radius: 12px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.image-delete {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		width: 40rpx;
		height: 40rpx;
		color: #ef4444;
	}


	/* --- 图标上传 --- */
	.icon-upload-group {
		display: flex;
		flex-direction: row;
		gap: 32rpx;
		align-items: center;
	}

	.icon-box {
		width: 200rpx;
		height: 200rpx;
		border-radius: 24rpx;
		background-color: #f3f4f6;
		border: 2rpx solid #e5e7eb;
		overflow: hidden;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		flex-shrink: 0;
	}

	.icon-preview {
		width: 100%;
		height: 100%;
	}

	.icon-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #9ca3af;
	}

	.icon-placeholder-icon {
		font-size: 60rpx;
		margin-bottom: 8rpx;
	}

	.icon-placeholder-text {
		font-size: 24rpx;
	}

	.icon-upload-tip {
		font-size: 28rpx;
		color: #6b7280;
	}

	.tip-paragraph {
		display: block;
	}

	/* --- 表单网格 --- */
	.grid-form {}

	.form-item {
		margin-bottom: 20rpx;
	}

	.col-span-2 {
		width: 100%;
	}

	.textarea-input {
		width: 100%;
		height: 300rpx;
		border: 2rpx solid #d1d5db;
		border-radius: 16rpx;
		padding: 24rpx;
		font-size: 30rpx;
		line-height: 1.5;
	}

	/* --- 平台多选 --- */
	.platform-checkbox-group {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		gap: 24rpx;
	}

	.platform-checked {
		/* 例如：将背景色改为品牌色，并增加边框 */
		background-color: #e0e7ff;
		/* 浅紫色 */
		border: 2rpx solid #4f46e5;
		/* 品牌色边框 */
		color: #4f46e5;
		/* 文本颜色改为品牌色 */
	}

	.platform-checkbox {
		display: flex;
		align-items: center;
		gap: 16rpx;
		background-color: #f3f4f6;
		border-radius: 9999rpx;
		padding: 8rpx 24rpx;
		font-size: 28rpx;
		color: #4b5563;
		flex-shrink: 0;
		transition: all 0.2s;
		/* 增加过渡效果 */
	}

	/* --- 底部固定栏 --- */
	.fixed-bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 1rpx solid #e5e7eb;
		padding: 32rpx;
		gap: 24rpx;
		z-index: 10;
	}

	.submit-btn-fixed {
		background-color: #0088FF;
		color: #ffffff;
		padding: 24rpx 48rpx;
		border-radius: 32rpx;
		font-weight: bold;
		font-size: 18px;
		line-height: 1;
		border: none;
		flex-shrink: 0;
	}

	.submit-btn-fixed::after {
		border: none;
	}


	/* --- 新增：单选样式 (是否官方正版) --- */
	.radio-group {
		display: flex;
		gap: 40rpx;
		padding-top: 10rpx;
	}

	.radio-item {
		display: flex;
		align-items: center;
		gap: 16rpx;
		font-size: 30rpx;
		color: #1f2937;
		cursor: pointer;
	}

	.radio-dot {
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
		border: 2rpx solid #d1d5db;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s;
	}

	.radio-dot-checked {
		border-color: #0088FF;
		background-color: #0088FF;
		position: relative;
	}

	.radio-dot-checked::after {
		content: '';
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: #ffffff;
		/* 内芯的颜色 */
		display: block;
	}
</style>